package com.example.hrsystem;

import android.app.Application;
import android.content.Context;
import android.os.Build;
import android.os.StrictMode;
import android.util.Log;
import android.widget.Toast;

import com.example.hrsystem.data.source.DatabaseInitializer;

import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * 自定义Application类
 * 用于初始化全局配置和捕获未处理的异常
 */
public class HRSystemApplication extends Application {

    private static final String TAG = "HRSystemApplication";
    private static Context appContext;

    @Override
    public void onCreate() {
        super.onCreate();
        appContext = getApplicationContext();
        
        // 启用严格模式以便发现潜在问题
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                .detectAll()
                .penaltyLog()
                .build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                .detectAll()
                .penaltyLog()
                .build());
        
        // 设置全局异常处理器
        setupGlobalExceptionHandler();
        
        // 初始化数据库并添加模拟数据
        Log.d(TAG, "初始化数据库...");
        DatabaseInitializer.initializeDatabase(this);
        
        // 数据库初始化完成
        
        Log.d(TAG, "Application initialized successfully");
    }

    /**
     * 设置全局异常处理器，捕获未处理的异常
     */
    private void setupGlobalExceptionHandler() {
        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread thread, Throwable throwable) {
                // 记录异常信息
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                throwable.printStackTrace(pw);
                String exceptionInfo = sw.toString();
                
                Log.e(TAG, "Uncaught Exception: " + exceptionInfo);
                
                // 在主线程显示错误提示
                Thread mainThread = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(appContext, "应用遇到问题，正在重启...", Toast.LENGTH_LONG).show();
                    }
                });
                mainThread.start();
                
                try {
                    // 延迟一小段时间让用户看到提示
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                
                // 这里可以选择重启应用或退出
                // 为了安全起见，我们选择退出而不是重启
                android.os.Process.killProcess(android.os.Process.myPid());
                System.exit(1);
            }
        });
    }

    /**
     * 获取全局Application Context
     */
    public static Context getAppContext() {
        return appContext;
    }
}